package org.hfchunya.mutualHelp.core.file.service;



import lombok.extern.slf4j.Slf4j;
import org.hfchunya.mutualHelp.core.file.model.FileUploadBean;
import org.hfchunya.mutualHelp.core.file.service.impl.EmptyBackUp;
import org.hfchunya.mutualHelp.core.file.util.FileUploadConstants;
import org.hfchunya.mutualHelp.core.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.File;
import java.security.SecureRandom;
import java.util.Date;


/**
 * <p>文件上传处理</p>
 *
 * @author MGary
 */
@Slf4j
@Service
public class FileUploadService {

    @Autowired
    private Environment env;

    private static final String ALIOSS = "aliyun";

    private static final String EMPTY = "empty";

    /**
     * <p>获取备份策略 </p>
     *
     * @param - <br/>
     * @return <br/>
     * @throws
     * @date 2019/2/27 15:03 <br/>
     */

    public IFileBackup getFileBackup() {
        IFileBackup fileBackup;

        String backupName = env.getProperty("oss");
        String id = env.getProperty("aliyun.id");

         if (EMPTY.equals(backupName)) {
            // 关闭备份
            fileBackup = new EmptyBackUp();
        } else {
            throw new RuntimeException("file backup get fail.");
        }
        return fileBackup;
    }




    /**
     * <p>上传文件处理 </p>
     *
     * @param projectStorePath - 当前文件地址 <br/>
     * @param uploadFile       - 文件流 <br/>
     * @return <br/>
     * @throws
     * @date 2019/2/27 19:12 <br/>
     */

    public FileUploadBean uploadHandle(String projectStorePath, File uploadFile, String fileAddress) {
        FileUploadBean bean = null;
        //获取项目路径
        try {
            // 文件重命名，避免中文保证唯一
            bean = rename(projectStorePath, uploadFile,fileAddress);
            // 文件备份
            getFileBackup().backup(bean);
        } catch (Exception e) {
            log.error("fileuploadservice uploadhandle fail.", e);
        }
        return bean;
    }


    /**
     * <p>重命名 </p>
     *
     * @param newPath -当前文件地址  <br/>
     * @param file    - 文件对象 <br/>
     * @return <br/>
     * @throws
     * @date 2019/2/27 19:12 <br/>
     */

    public static FileUploadBean rename(String newPath, File file,String fileAddress) {
        if (!file.exists()) {
            throw new RuntimeException("file is not exist , filepath:" + file.getAbsolutePath());
        }
        newPath = rebuildNoDecode(newPath);
        File uploadPath = new File(newPath);
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }

        //获取文件名称全称
        String originalName = file.getName();
        //获取文件名
        String originalFileName = null;
        //文件后缀
        String fileExt = null;
        //拆分文件
        int dot = originalName.lastIndexOf(".");
        if (dot != -1) {
            originalFileName = originalName.substring(0, dot);
            fileExt = originalName.substring(dot + 1);
        } else {
            originalFileName = originalName;
            fileExt = "";
        }

        String fileAddressName = fileAddress.substring(0,fileAddress.lastIndexOf("/"));


        // 改名,避免重复以及中文问题
        String fileName = DateUtils.getNow("yyyyMMdd_HHmmss") + "_" //
                + new SecureRandom().nextInt(999999) + "." + fileExt;
        String newFilePath = newPath + "/" + fileName;
        File newFile = new File(newFilePath);
        if (!file.renameTo(newFile)) {
            throw new RuntimeException("file rename fail , oldfile:" + file.getAbsolutePath()
                    + " -> newfile:" + newFile.getAbsolutePath());
        }

        // 创建对象
        FileUploadBean bean = new FileUploadBean();
        bean.setName(fileName);
        bean.setFactpath(newFilePath);
        bean.setExt(fileExt);
        bean.setOriginalName(originalFileName + "." + fileExt);
        bean.setType(FileUploadConstants.getFileType(fileExt));
        bean.setSize(newFile.length());
        bean.setFileAddress(fileAddressName+ "/" + fileName);
        return bean;
    }

    /**
     * <p> 将File转换为FileUploadBean</p>
     *
     * @param file - 文件 <br/>
     * @return <br/>
     * @throws
     * @date 2019/2/27 19:15 <br/>
     */

    public FileUploadBean getFileUploadBean(File file) {
        String originalName = file.getName();
        String originalFileName = null;
        String fileExt = null;
        int dot = originalName.lastIndexOf(".");
        if (dot != -1) {
            originalFileName = originalName.substring(0, dot);
            fileExt = originalName.substring(dot + 1);
        } else {
            originalFileName = originalName;
            fileExt = "";
        }

        // 创建对象
        FileUploadBean bean = new FileUploadBean();
        bean.setName(originalName);
        bean.setFactpath(file.getAbsolutePath());
        bean.setExt(fileExt);
        bean.setOriginalName(originalFileName + "." + fileExt);
        bean.setType(FileUploadConstants.getFileType(fileExt));
        bean.setSize(file.length());
        return bean;
    }

    /**
     * 重构路径
     *
     * 2017年4月5日 下午1:55:59 flyfox 369191470@qq.com
     *
     * @param path
     * @return
     */
       public static String rebuildNoDecode(String path) {
        String newPath = path;
        newPath = newPath.replaceAll("\\\\", "/");
        newPath = newPath.replaceAll("//", "/");

        return newPath;
    }


}
